package com.mine.modules.vm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mine.common.utils.IpUtils;
import com.mine.common.utils.SpringContextUtils;
import com.mine.common.utils.oConvertUtils;
import com.mine.modules.sys.utils.ListUtils;
import com.mine.modules.vm.entity.VmPermissionLayer;
import com.mine.modules.vm.entity.VmRolePermission;
import com.mine.modules.vm.mapper.VmRolePermissionMapper;
import com.mine.modules.vm.service.IVmRolePermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色权限表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-15
 */
@Service
public class VmRolePermissionServiceImpl extends ServiceImpl<VmRolePermissionMapper, VmRolePermission> implements IVmRolePermissionService {

    @Override
    public void saveRolePermission(String roleId, String permissionIds, String lastPermissionIds) {
        String ip = "";
        try {
            //获取request
            HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
            //获取IP地址
            ip = IpUtils.getIpAddr(request);
        } catch (Exception e) {
            ip = "127.0.0.1";
        }
        List<String> add = ListUtils.getDiff(lastPermissionIds, permissionIds);
        if (add != null && !add.isEmpty()) {
            List<VmRolePermission> list = new ArrayList<>();
            for (String p : add) {
                if (oConvertUtils.isNotEmpty(p)) {
                    VmRolePermission vmRolePermission = lambdaQuery()
                            .eq(VmRolePermission::getRoleId, roleId)
                            .eq(VmRolePermission::getPermissionId, p).one();
                    if (vmRolePermission == null) {
                        VmRolePermission rolePms = new VmRolePermission(roleId, p);
                        rolePms.setOperateDate(new Date());
                        rolePms.setOperateIp(ip);
                        list.add(rolePms);
                    }
                }
            }
            this.saveBatch(list);
        }
        List<String> delete = ListUtils.getDiff(permissionIds, lastPermissionIds);
        if (delete != null && !delete.isEmpty()) {
            for (String permissionId : delete) {
                this.remove(new QueryWrapper<VmRolePermission>().lambda().eq(VmRolePermission::getRoleId, roleId).eq(VmRolePermission::getPermissionId, permissionId));
            }
        }
    }

    @Override
    public List<String> getPermissionIdsByRoleIds(List<String> roleIds) {
        return lambdaQuery()
                .in(roleIds != null, VmRolePermission::getRoleId, roleIds)
                .list()
                .stream()
                .map(VmRolePermission::getPermissionId)
                .collect(Collectors.toList());
    }

}
